package com.madao.im.response;

import com.madao.im.config.constant.ErrorCode;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.util.List;

/**
 * json 返回
 *
 * @author chengjunchao
 * @version 1.0.0
 * @date 2021/12/6 14:13
 */
public class JsonResponse<T> {
    private static <T> ResponseEntity<T> response(T data, String message, int code) {
        JsonData<T> jd = new JsonData<>();
        jd.setData(data);
        jd.setCode(code);
        jd.setMessage(message);
        return new ResponseEntity<>((T) jd, HttpStatus.OK);
    }

    private static <T> ResponseEntity<T> pageResponse(List<T> data, Long total, int code, String message) {
        PageData<T> pageData = new PageData<>();
        pageData.setData(data);
        pageData.setTotal(total);
        pageData.setCode(code);
        pageData.setMessage(message);
        return new ResponseEntity<>((T) pageData, HttpStatus.OK);
    }

    /**
     * 成功 message默认OK
     *
     * @param data
     * @return
     */
    public static <T> ResponseEntity<T> success(T data) {
        return response(data, JsonData.CODE_SUCCESS_MESSAGE, JsonData.CODE_SUCCESS);
    }

    /**
     * 成功
     *
     * @return data
     */
    public static <T> ResponseEntity<T> success() {
        return response(null, JsonData.CODE_SUCCESS_MESSAGE, JsonData.CODE_SUCCESS);
    }

    /**
     * 成功
     *
     * @param data
     * @param message
     * @return
     */
    public static <T> ResponseEntity<T> success(T data, String message) {
        return response(data, message, JsonData.CODE_SUCCESS);
    }

    /**
     * 失败
     *
     * @param code 错误码
     * @return
     */
    public static <T> ResponseEntity<T> fail(Integer code) {
        return response(null, ErrorCode.getMsg(code), code);
    }

    /**
     * 失败 带 data
     *
     * @param code 错误码
     * @return
     */
    public static <T> ResponseEntity<T> fail(Integer code, T data) {
        return response(data, ErrorCode.getMsg(code), code);
    }

    /**
     * 分页 返回成功
     *
     * @param data
     * @param total
     * @param <T>
     * @return
     */
    public static <T> ResponseEntity<T> success(List<T> data, Long total) {
        return pageResponse(data, total, JsonData.CODE_SUCCESS, JsonData.CODE_SUCCESS_MESSAGE);
    }

    /**
     * 分页返回失败
     *
     * @param data
     * @param total
     * @param code  错误码
     * @param <T>
     * @return
     */
    public static <T> ResponseEntity<T> fail(List<T> data, Long total, Integer code) {
        return pageResponse(data, total, code, ErrorCode.getMsg(code));
    }

}
